package com.sgai.zero_robot.ui.alarm;

import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.text.TextUtils;
import com.google.gson.Gson;
import com.sgai.zero_robot.pojo.AlarmInfo;
import com.sgai.zero_robot.ui.alarm.bean.FileInfo;
import java.io.File;
import java.util.LinkedList;

/**
 * Describe :
 * Created by zzw on 2024/8/28
 */
public class AlarmHandler extends Handler  {
    private final int CREATFILE = 1;
    private final int PRINT_MESSAGE = 2;
    private File file;
    private LinkedList<AlarmInfo> cache = new LinkedList<>();

    public AlarmHandler(Looper looper) {
        super(looper);
    }


    public void print(AlarmInfo msg) {
        Message message = obtainMessage();
        message.what = PRINT_MESSAGE;
        message.obj = msg;
        sendMessage(message);
    }
    public void setPath(String path) {
        if (TextUtils.isEmpty(path)){
            return;
        }
        Message message = obtainMessage();
        message.what = CREATFILE;
        message.obj = new FileInfo(path);
        sendMessage(message);
    }

    @Override
    public void handleMessage(Message msg) {
        super.handleMessage(msg);
        if (msg.what == CREATFILE){
            FileInfo fileInfo = (FileInfo) msg.obj;
            File file = new File(fileInfo.getFilePath());
            if (!file.exists()){
                boolean isCreate = FileUtils.createFile(file);
                if (isCreate){
                    this.file = file;
                }
            }else{
                this.file = file;
            }
        }else if (msg.what == PRINT_MESSAGE){
            AlarmInfo logInfo = (AlarmInfo) msg.obj;
            if (file == null || !file.exists()){
                if (cache.size()>100){
                    cache.removeFirst();
                }
                cache.add(logInfo);
                return;
            }
            if (cache.size()>0){
                for (AlarmInfo logInfo1:cache){
                    writeLog(logInfo1);
                }
            }
            cache.clear();
            writeLog(logInfo);
        }
    }
    Gson gson = new Gson();
    private void writeLog(AlarmInfo logInfo){
        String json = gson.toJson(logInfo)+"\r\n";
        FileUtils.saveStringToFile(file, json);
    }

}
